import jwt
from fastapi import HTTPException, Cookie
from starlette import status
from Model.default import get_db
from Model.user.User import user
from config.app_static_ import SECRET_KEY, ALGORITHM


PUBLIC_KEY = []
PRIVATE_KEY=[]
# 权限设置
async def judge_token(access_token: str = Cookie(None)):
    if not access_token:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated",
            headers={"WWW-Authenticate": "Bearer"})
    try:
            db=get_db()
            # 去掉 "Bearer " 前缀
            if access_token.startswith("Bearer "):
                access_token = access_token[7:]

            payload = jwt.decode(access_token, SECRET_KEY, algorithms=[ALGORITHM])
            account=payload.get('sub')
            user_data=db.query(user).filter_by(account=account).first()

    except jwt.PyJWTError:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid token",
            )
    return {
                'status': 'valid',
                'user': user_data,
    }
